package controllers

import (
	"HomeMaterialManagementSystem/db"
	"HomeMaterialManagementSystem/models"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func Login(c *gin.Context) {
	if c.Request.Method == http.MethodGet {
		c.HTML(http.StatusOK, "login.html", gin.H{
			"title": "登录",
		})
	} else if c.Request.Method == http.MethodPost {
		name := c.Request.FormValue("name")
		pwd := c.Request.FormValue("pwd")
		if name == "" || pwd == "" {
			c.Redirect(http.StatusFound, "/login")
			return
		}

		orm := db.GetORM()
		u := models.User{}
		orm.Where(&models.User{Name: name, Password: pwd}).First(&u)
		if u.ID == 0 {
			c.Redirect(http.StatusFound, "/login")
			return
		}
		now := time.Now()
		orm.Delete(models.Session{}, "name = ?", u.Name)
		session := models.Session{User: u, CreateTime: &now}
		session.SessionText = uuid.New().String()
		orm.Create(&session)
		c.SetCookie("hmmssession", session.SessionText, 36000, "/", "*.zhangman.love", false, true)
		c.Redirect(http.StatusFound, "/")
	} else {
		c.Redirect(http.StatusFound, "/login")
	}
}

func Logout(c *gin.Context) {
	sessionText, err := c.Cookie("hmmssession")
	if err != nil {
		c.Redirect(http.StatusFound, "/login")
		return
	}
	db.GetORM().Where(&models.Session{SessionText: sessionText}).Delete(models.Session{})
	c.Redirect(http.StatusFound, "/login")
}
